#include<stdio.h>
#include<pthread.h>

int counter=0;//0表示没有饭，1表示有饭
pthread_mutex_t mutex;
//定义两个条件变量
pthread_cond_t cook_cond;
pthread_cond_t cus_cond;

void*customer(void*arg)
{
  while(1)
  {
    pthread_mutex_lock(&mutex);
    //如果当前没饭，则顾客被阻塞
    while(counter<=0)
    {
      //保证解锁和休眠的原子性
      pthread_cond_wait(&cus_cond,&mutex);//阻塞步骤：先解锁，后等待，被唤醒后加锁
    }
    printf("我吃完了，再来一碗:%d\n",counter);
    counter--;
    pthread_cond_signal(&cook_cond);  //唤醒厨师
    pthread_mutex_unlock(&mutex);
  }
  return NULL;
}

void*cook(void*arg)
{
  while(1)
  {
    pthread_mutex_lock(&mutex);
    //如果当前有饭，则厨师阻塞
    while(counter>0)
    {
      pthread_cond_wait(&cook_cond,&mutex);
    }
    printf("饭做好了，快来吃饭:%d\n",counter);
    counter++;
    pthread_cond_signal(&cus_cond);//唤醒顾客
    pthread_mutex_unlock(&mutex);
  }
  return NULL;
}
int main()
{
  pthread_t cus_tid[4],cook_tid[4];
  pthread_mutex_init(&mutex,NULL);
  pthread_cond_init(&cus_cond,NULL);
  pthread_cond_init(&cook_cond,NULL);
  int ret;

  //创建线程
  for(int i=0;i<4;++i)
  {
    ret=pthread_create(&cus_tid[i],NULL,customer,NULL);
    if(ret!=0)
    {
      perror("creat error");
      return -1;
    }
    ret=pthread_create(&cook_tid[i],NULL,cook,NULL);
    if(ret!=0)
    {
      perror("creat error");
      return -1;
    }
  }
  //等待所有线程退出
  for(int i=0;i<4;++i)
  {
    pthread_join(cus_tid[i],NULL);
    pthread_join(cook_tid[i],NULL);
  }
  //销毁条件变量
  pthread_cond_destroy(&cus_cond);
  pthread_cond_destroy(&cook_cond);
  return 0;
}
